﻿using System;
using Common.Commands;
using Common.Commands.TrackLogCommands;
using Core.Domain.Model;
using Dto.ApiResponses.TrackLogResponses;
using Sanelib.Common.Helpers;
using Sanelib.DataOperation;

namespace Core.Processors.TrackLogProcessors
{
    public class AddTrackLogProcessor : ICommandProcessor<AddTrackLog>
    {
        private readonly IRepository<TrackLog> _trackLogsRepository;
        private readonly IRepository<Member> _memberRepository;

        public AddTrackLogProcessor(IRepository<TrackLog> trackLogsRepository, IRepository<Member> memberRepository)
        {
            _trackLogsRepository = trackLogsRepository;
            _memberRepository = memberRepository;
        }

        public dynamic Process(AddTrackLog command)
        {
            var member = _memberRepository.GetByKey(Property.Of<Member>(x => x.TagId), command.TagId);

            if (member == null)
            {
                throw new Exception("Member not found for tag: " + command.TagId);
            }

            var trackLog = new TrackLog
                {
                    Id = command.Id,
                    Name = member.Name,
                    Code = member.Code,
                    DetectedOn = command.DetectedOn,
                    CreatedBy = command.UserId,
                    ImageData = command.ImageData,
                    Description = command.Description
                };

            _trackLogsRepository.Add(trackLog);

            var trackLogResponse = new TrackLogResponse
            {
                Id = command.Id,
                Name = trackLog.Name,
                Code = trackLog.Code,
                RedirectRequired = false,
                DetectedOn = command.DetectedOn,
            };

            return trackLogResponse;
        }
    }
}
